import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/store/auth'

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/view/Home.vue'),
    meta: {
      title: '首页',
      requiresAuth: false
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/view/Login.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/view/Register.vue'),
    meta: {
      title: '注册',
      requiresAuth: false
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/view/Profile.vue'),
    meta: {
      title: '个人中心',
      requiresAuth: true
    }
  },
  {
    path: '/post/create',
    name: 'PostCreate',
    component: () => import('@/view/PostCreate.vue'),
    meta: {
      title: '发布文章',
      requiresAuth: true
    }
  },
  {
    path: '/article/:id',
    name: 'ArticleDetail',
    component: () => import('@/view/ArticleDetail.vue'),
    meta: {
      title: '文章详情',
      requiresAuth: false
    }
  },
  {
    path: '/study',
    name: 'StudyCheckIn',
    component: () => import('@/view/StudyCheckIn.vue'),
    meta: {
      title: '学习打卡',
      requiresAuth: true
    }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('@/view/Admin.vue'),
    meta: {
      title: '后台管理',
      requiresAuth: true
    }
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/view/error/403.vue'),
    meta: {
      title: '无权限'
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/view/error/404.vue'),
    meta: {
      title: '页面不存在'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title || '博客系统'

  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const authStore = useAuthStore()

    if (!authStore.isLoggedIn) {
      // 未登录，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router